package com.wu.leetcode.leetcode116;

/**
 * Leetcode116-填充每个节点的下一个右侧节点指针
 *
 * @author lynn
 * @date 2020/11/6 - 13:47
 */
// Definition for a Node.
class Node {
    public int val;
    public Node left;
    public Node right;
    public Node next;

    public Node() {
    }

    public Node(int _val) {
        val = _val;
    }

    public Node(int _val, Node _left, Node _right, Node _next) {
        val = _val;
        left = _left;
        right = _right;
        next = _next;
    }
};


class Solution {
    public Node connect(Node root) {
        if (root == null) {
            return root;
        }
      /*  LinkedList<Node> queue = new LinkedList<>();
        queue.add(root);
        while (queue.size() > 0) {
            int size = queue.size();
            Node node = queue.get(0);

            for (int i = 1; i < size; ++i) {
                node.next = queue.get(i);
                node = queue.get(i);
            }
            for (int i = 0; i < size; ++i) {
                node = queue.remove();
                if (node.left != null) {
                    queue.add(node.left);
                }
                if (node.right != null) {
                    queue.add(node.right);
                }
            }
        }
        return root;*/
        Node tmp = root;
        while (tmp.left != null) {
            Node cur = tmp;
            while (cur != null) {
                cur.left.next = cur.right;
                if (cur.next != null) {
                    cur.right.next = cur.next.left;
                }
                cur = cur.next;
            }
            tmp = tmp.left;
        }
        return root;
    }
}
